<?php

namespace App\Http\Controllers\Api;


use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Models\Api\Histroy;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Controllers\utils\Common;

class HistoryController extends BaseController
{

    function __construct()
    {
        $this->common = new Common();
    }
    /**
     * Display a listing of the resource.
     *
     * api/v1/history GET
     */
    public function index(Request $request)
    {
        try {
            // // 尝试从请求中获取 Token
            // $token = JWTAuth::parseToken();

            // // 通过 Token 获取经过身份验证的用户
            // $user = $token->authenticate();

            $params = $request->all();
            $limit = isset($params['limit']) ? $params['limit'] : 10;

            $data =  Histroy::simplePaginate($limit);

            return $this->responseData($data, '获取成功', 200);

            // 在这里使用 $user 即可
        } catch (JWTException $e) {
            // 处理 Token 解析失败的情况
            return response()->json(['error' => 'Token 无效'], 401);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * api/v1/history  POST
     */
    public function store(Request $request)
    {
        $validateList = [
            "questionids" => "required",
            "userid" => "required",
            "flag" => 'required',
            "score" => 'required'
        ];
        $endParams = $request->all();
        $endParams['time'] =  now();
        $endParams['status'] = 1;
        return $this->common->apiAdd(Histroy::class, $request, $validateList, $endParams);
    }

    /**
     * Display the specified resource.
     *
     * api/v1/history/userid  GET
     */
    public function show(Request $request, string $userid)
    {
        //
        $params = $request->all();
        $limit = isset($params['limit']) ? $params['limit'] : 10;

        $data =  Histroy::where('userid', $userid)->orderBy('time', 'desc')->simplePaginate($limit);
        return $this->responseData($data, '获取成功', 200);
    }

    /**
     * Update the specified resource in storage.
     *
     * api/v1/history/id  PUT
     */
    public function update(Request $request, string $id)
    {
        return $this->common->apiEdit(Histroy::class, $request, $id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * api/v1/history/id  delete
     */
    public function destroy(Request $request, string $id)
    {
        return $this->common->apiDelete(Histroy::class, $request, $id);
    }
}
